<template>
    <div>
        <!-- 面包屑导航条位置 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片内容区域 -->
        <el-card class="box-card" >     
            <!-- 警告区域 -->
            <el-alert
            show-icon
            :closable="false"
            title="注意：只允许为第三季分类设置相关参数"
            type="warning">
            </el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="Choice">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 分类选择框 -->
                    <el-cascader     
                        clearable
                        :props="cascaderProps"
                        :options="cateList"                    
                        v-model="selectedOptions2"
                        @change="handleChange">
                    </el-cascader> 
                </el-col>
            </el-row>

            <!-- tabs页签区域 -->
             <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addialogVisible=true" >添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe >
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="handleClose(i,scope.row)" closable v-for="(item, i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                          <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showmodifyParams(scope.row.attr_id)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsById(scope.row.attr_id)"></el-button>
                          </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addialogVisible=true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="handleClose(i,scope.row)" closable v-for="(item, i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                          <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showmodifyParams(scope.row.attr_id)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsById(scope.row.attr_id)"></el-button>
                          </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
                 
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addialogVisible"
        width="50%"
        @close="addDialogClosed"
        >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParamsForm">确 定</el-button>
        </span>
        </el-dialog>

        <!-- 修改参数对话框 -->
        <el-dialog
        :title="'修改'+titleText"
        :visible.sync="modifyDialogVisible"
        width="50%"
        @close="modifyDialogClosed"
        >
        <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="modifyForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="modifyDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyParamsForm">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // //控制输入框的显示,解决bug在methods中定义
            // inputVisible: false,
            // //文本框输入数据
            // inputValue: '',
            //标签页数据
            activeName: "many",
            cateList: [],
            //父级选择框的渲染数据
            //双向绑定选择框的数据
            selectedOptions2: [],
            //动态参数
            manyTableData: [],
            //静态属性
            onlyTableData: [],
             //指定选择器的配置对象
            cascaderProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: "hover",               
            },
            //控制对话框的显示与隐藏
            addialogVisible: false,
            modifyDialogVisible: false,

            //添加参数的表单数据对象
            addForm: {
                attr_name: ''
            },
            addFormRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' },
                ]
            },
            //修改参数的表单数据对象
            modifyForm: {},
            modifyFormRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' },
                ]
            }

        }
    },
    created () {
        this.getCateList()
        
    },
    methods: {
        async getCateList () {
          const {data: res} = await this.$http.get('categories')
          if(res.meta.status !== 200) return this.$message.error('获取商品分类数据失败')
            this.cateList = res.data           
        },
        async handleChange () {
            
            if(this.selectedOptions2.length !== 3){
                this.selectedOptions2 = []
                this.manyTableData = []
                this.onlyTableData = [] 
                return 
            } 
            //根据当前所选的id，和所处的面板，发起请求
            // console.log(this.activeName)
            this.getParamsData()
        },
        async getParamsData () {
            const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: this.activeName}})
            if(res.meta.status !== 200) return this.$message.error('获取参数失败')
            // console.log(res.data)
            // 赋值之前循环出attr_vals,将其变成数组
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

                //解决bug，将data中的inputvisible进行处理
                item.inputVisible = false
                item.inputValue = ''
            })

            //判断当前数据是哪个的，要给谁
            if(this.activeName === 'many'){
                this.manyTableData = res.data
            }else{
                this.onlyTableData = res.data
            }
        },
        //页签点击事件
        handleClick () {
            if(this.cateId === null) return false
            this.getParamsData()
        },
        //窗口关闭
        addDialogClosed () {
           this.$refs.addFormRef.resetFields() 
        },
        //提交表单
        addParamsForm () {
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return
                const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                })
                if(res.meta.status !==201) return this.$message.error('添加失败')
                this.$message.success('添加成功')
                
                this.getParamsData()
                this.addialogVisible = false
            })
        },
        //删除动态参数
        async removeParamsById (id) {
            
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)//.catch()捕获错误信息并返回

            if(confirmResult !== 'confirm'){
                return this.$message.info('已经取消了删除')
            }
            //确定删除操作
            const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
            if(res.meta.status !== 200) return this.$message.error('删除角色失败') 
            this.$message.success('成功删除角色')
            this.getParamsData()        
        },
        //显示修改对话框
        async showmodifyParams (id) {
            this.modifyDialogVisible = true
            const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${id}`)
            if(res.meta.status !== 200) return this.$message.error('获取修改信息失败')
        
            //存放要修改的数据的面板
            this.modifyForm = res.data
        },
        //提交修改内容 
        modifyParamsForm () {
            console.log(this.modifyForm.attr_id)
            console.log(this.modifyForm.attr_name)
            //检验信息规则
            this.$refs.modifyFormRef.validate(async valid =>{
                if(!valid) return
                const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.modifyForm.attr_id}`,this.modifyForm)
                if(res.meta.status !==200) return this.$message.error('修改信息失败')
                this.$message.success('修改信息成功')
                this.getParamsData()
                this.modifyDialogVisible = false
            })            
        },
        modifyDialogClosed () {
            this.$refs.modifyFormRef.resetFields()
        },
        //文本框数去焦点，或者按下enter都会触发
        async handleInputConfirm (row) {
            //验证是否输入了内容，清除空格
            if(row.inputValue.trim().length === 0){
                row.inputValue = '' 
                row.inputVisible = false
                return
            }
            //没有return,说明输入合法
            row.attr_vals.push(row.inputValue)
            row.inputValue = ''
            row.inputVisible = false 
            //发起请求，保存数据
            // const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            //     attr_name: row.attr_name,
            //     attr_sel: row.attr_sel,
            //     attr_vals: row.attr_vals.join(' ')
            // })  
            // if(res.meta.status !== 200) return this.$message.error('修改失败')
            // this.$message.success('修改成功')
            this.saveAttrVals(row)     
        },
        //点击按钮，显示输入文本框
        showInput (row) {
            row.inputVisible = true
            //当页面重新被渲染之后才调用
            this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
        },
        //保存操作
        async saveAttrVals (row) {
             //发起请求，保存数据
            const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })  
            if(res.meta.status !== 200) return this.$message.error('修改失败')
            this.$message.success('修改成功')
        },
        //删除对应的可选性
        handleClose (i, row) {
            row.attr_vals.splice(i, 1)
            this.saveAttrVals(row)
        }
    },
    computed: {
        //计算属性来控制按钮的启用与禁用
        isBtnDisabled () {
            if(this.selectedOptions2.length !== 3){
                return true
            }
            return false
        },
        // 获取当前选中的三级分类的id
        cateId() {
            if(this.selectedOptions2.length === 3){
                return this.selectedOptions2[2]
            }
            return null
        },
        titleText () {
            if(this.activeName === 'many'){
                return '动态参数'
            }
            return '静态属性'
        }
    }
};
</script>

<style scoped lang="scss">
.Choice{
    margin: 10px 0;
}
.el-tag {
    margin-left: 8px;
}
.el-cascader{
    width: 40%;
}
.input-new-tag {
    width: 120px !important;
    margin-left: 8px;
}
.button-new-tag {
   margin-left: 8px; 
}
</style>
